<template>
  <c-loading :loading="loading">
    <view class="container after-info">
      <view class="after-top block">
        <view class="status" :class="afterStatusColor(after)">{{ after.afterStatusName }}</view>
        <view class="desc">{{ getAfterDesc(after) }}</view>
      </view>
      <view class="after-item block">
        <c-img class="img" :src="after.smallImg" />
        <view class="body grow">
          <view class="goods-name row2">{{ after.goodsName }}</view>
          <view class="flex-between al-center">
            <view class="sku-name">{{ after.skuDesc }}</view>
            <view class="qty">x{{ after.afterQty }}</view>
          </view>
          <view class="last">
            <view class="type">
              {{ after.afterTypeName }}
            </view>
            <c-number v-if="after.refundPrice" class="price" prefix="￥" :value="after.refundPrice" :precision="2" />
          </view>
        </view>
      </view>
      <view class="block pad" v-if="after.returnAddress">
        <view class="title">退回地址</view>
        <view
          class="address-wrap"
          @tap="copy(`${after.returnAddress.consignee} ${after.returnAddress.consigneePhone} ${after.returnAddress.region.join('')}${after.returnAddress.address}`)"
        >
          <c-icon size="40" icon="location" />
          <view class="address-box">
            <view class="consignee">
              <text class="name">{{ after.returnAddress.consignee }}</text>
              <text>{{ after.returnAddress.consigneePhone }}</text>
            </view>
            <view class="row2 address">{{ after.returnAddress.region?.join('') + after.returnAddress.address }}</view>
          </view>
          <c-icon color="var(--color-primary)" icon="file-copy" />
        </view>
      </view>
      <view class="block box">
        <view class="row">
          <view class="label">售后类型</view>
          <view class="value">{{ after.afterTypeName }}</view>
        </view>
        <view class="row">
          <view class="label">退款金额</view>
          <view class="value"><c-number :value="after.refundPrice" /></view>
        </view>
        <view class="row">
          <view class="label">售后原因</view>
          <view class="value">{{ after.afterReason }}</view>
        </view>
        <view class="row break">
          <view class="label">图片说明</view>
          <view class="value">
            <c-upload v-model="after.afterImgs" :max-count="10" disabled />
          </view>
        </view>
      </view>
      <view class="block box">
        <view class="row" @tap="copy(after.afterNo)">
          <view class="label">售后单号</view>
          <view class="grow"></view>
          <view class="value">{{ after.afterNo }}</view>
          <c-icon color="var(--color-primary)" icon="file-copy" />
        </view>
        <view class="row">
          <view class="label">申请时间</view>
          <view class="value">
            {{ after.createTime }}
          </view>
        </view>
        <view class="row" v-if="after.returnTime">
          <view class="label">退货时间</view>
          <view class="value">
            {{ after.returnTime }}
          </view>
        </view>
        <view class="row" v-if="after.reDeliveryTime">
          <view class="label">发货时间</view>
          <view class="value">
            {{ after.reDeliveryTime }}
          </view>
        </view>
        <view class="row" v-if="after.reSignTime">
          <view class="label">签收时间</view>
          <view class="value">
            {{ after.reSignTime }}
          </view>
        </view>
        <!-- <view class="row" v-if="after.finishTime">
          <view class="label">结束时间</view>
          <view class="value">
            {{ after.finishTime }}
          </view>
        </view> -->
        <view class="row" v-if="after.refundTime">
          <view class="label">退款时间</view>
          <view class="value">
            {{ after.refundTime }}
          </view>
        </view>
      </view>
      <view class="fixed-footer flex al-center shadow" v-if="after.afterStatus <= 1 || (logistics.length && after.afterStatus < 20)">
        <view class="grow"></view>
        <c-button size="inline" v-if="after.afterStatus <= 1" type="warn" plain @tap="onCancel(after)">取消申请</c-button>
        <c-button size="inline" v-if="after.afterStatus == 1" type="primary" @tap="toSubmitLog(after)">填写物流单号</c-button>
        <c-button size="inline" v-if="logistics.length && after.afterStatus < 20" type="primary" plain @tap.stop="lookDelivery(after)">查看物流</c-button>
        <c-button size="inline" v-if="after.reDeliveryTime && !after.reSignTime" type="primary" plain @tap.stop="signFor(after)">确认签收</c-button>
      </view>
      <view class="end"></view>
    </view>
  </c-loading>
</template>
<script setup>
import { CButton, CLoading, CIcon, CImg, CNumber, CUpload } from '@/components';
import { useLoading, timeCountdown, hideMobile, useRouter } from '@/hooks';
import { View } from '@tarojs/components';
import { setClipboardData, usePullDownRefresh, stopPullDownRefresh, useDidShow, useUnload, useDidHide, navigateToMiniProgram, showActionSheet } from '@tarojs/taro';
import api from '@/api';
import { ref } from 'vue';
import toast from '@/utils/toast';

const router = useRouter();
const now = ref(Date.now() / 1000);
let t;
const after = ref({});
const logistics = ref([]);
const { loading, restart } = useLoading(async options => {
  after.value = await api.order.aftersalesInfo({
    afterNo: options.id
  });
  if (after.value.returnTime || after.value.reDeliveryTime) {
    logistics.value = await api.order.getlogistics({
      afterOrderNo: after.value.afterNo
    });
  }
});
const copy = e => {
  setClipboardData({
    data: e,
    success() {
      toast.success('复制成功');
    }
  });
};

const onCancel = (a, i) => {
  toast.confirm('确认取消申请').then(() => {
    toast.loading.lock(() =>
      api.order
        .aftersalesCancel({
          id: a.afterNo
        })
        .success('取消成功', true)
        .then(() => {
          restart();
          router.callback(after.value);
        })
    );
  });
};

const toSubmitLog = a => {
  router.push(`/pagesOrder/aftersales/return?afterNo=${a.afterNo}&orderNo=${a.orderNo}`).then(data => {
    restart();
    router.callback(after.value);
  });
};

const toDeliveryApp = expressNo => {
  navigateToMiniProgram({
    appId: 'wx6885acbedba59c14',
    path: 'pages/result/result?nu=' + expressNo,
    extraData: {
      nu: expressNo
    },
    envVersion: 'release',
    success(res) {
      // 打开成功
    }
  });
};
const lookDelivery = a => {
  if (logistics.value.length == 1) {
    toDeliveryApp(logistics.value[0].logisticsNo);
  } else {
    showActionSheet({
      itemList: logistics.value.map(a => a.logisticsNo),
      success(r) {
        toDeliveryApp(logistics.value[r.tapIndex].logisticsNo);
      }
    });
  }
};

const signFor = (after, i) => {
  toast.confirm('确认已收到货').then(data => {
    toast.loading.lock(() =>
      api.order
        .aftersalesExchangeSignFor({ id: after.afterNo })
        .toast('签收成功', true)
        .then(() => {
          restart();
          router.callback(after.value);
        })
    );
  });
};

useDidShow(() => {
  now.value = Date.now() / 1000;
  t = setInterval(() => {
    now.value = Date.now() / 1000;
  }, 1000);
});
useUnload(() => {
  t && clearInterval(t);
  t = 0;
});
useDidHide(() => {
  t && clearInterval(t);
  t = 0;
});
const afterStatusColor = after => {
  switch (after.afterStatus) {
    case 0:
    case 5:
    case 10:
    case 11:
      return 'color-warn';
    case 30:
      return 'color-danger';
    case 31:
      return 'color-gray';
    default:
      return 'color-primary';
  }
};

let isIn = false;
const startReload = async () => {
  if (isIn) {
    return;
  }
  isIn = true;
  for (let i = 0; i < 3; i++) {
    await restart();
    await Promise.sleep(5000);
    if (after.value.afterStatus == 10 || after.value.afterStatus >= 20) break;
  }
  isIn = false;
};
usePullDownRefresh(async () => {
  await restart();
  stopPullDownRefresh();
});
const getAfterDesc = after => {
  switch (after.afterStatus) {
    case 0:
      if (after.operationExpiredTimestamp < now.value) {
        startReload();
      }
      return `离自动处理还剩：${timeCountdown(after.operationExpiredTimestamp, now.value)}`;
    case 1:
      if (after.operationExpiredTimestamp < now.value) {
        startReload();
      }
      return `请将商品退回，还剩${timeCountdown(after.operationExpiredTimestamp, now.value)}自动取消`;
    case 5:
      if (after.operationExpiredTimestamp < now.value) {
        startReload();
      }
      return `商品已退回，离自动处理还剩：${timeCountdown(after.operationExpiredTimestamp, now.value)}`;
    case 10:
      return '商家同意申请，等待商家重新发货';
    case 15:
      if (after.operationExpiredTimestamp < now.value) {
        startReload();
      }
      return `商品已寄出，还剩${timeCountdown(after.operationExpiredTimestamp, now.value)}自动签收`;
    case 20:
      return after.refundPrice > 0 ? (after.isRefund ? '系统已退款成功。' : '系统退款中，请稍后...') : '商品已签收';
    case 30:
      return '拒绝原因：' + after.refuseReason;
    default:
      return '';
  }
};
</script>
<style lang="scss">
.after-info.container {
  .after-top {
    padding: 10px 30px 30px;
    .status {
      font-size: 40px;
      font-weight: bold;
      margin-bottom: 16px;
    }
    .desc {
      font-size: 24px;
      color: var(--color-gray);
    }
  }
  .after-item {
    background-color: #fff;
    display: flex;
    align-items: stretch;
    padding: 30px 30px 30px;
    .img {
      flex-shrink: 0;
      width: 160px;
      height: 160px;
      margin-right: 20px;
      overflow: hidden;
      border-radius: 10px;
    }
    .body {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .goods-name {
        flex-grow: 1;
      }
      .sku-name {
        display: inline-block;
        line-height: 36px;
        height: 36px;
        font-size: 22px;
        color: var(--color-gray);
        &:last-of-type {
          margin-right: 0;
        }
      }
      .price {
        color: var(--color-danger);
      }
      .last {
        margin-top: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .type {
          background-color: var(--color-primary);
          color: var(--color-caption);
          font-size: 22px;
          padding: 0 15px;
          line-height: 36px;
          border-radius: 6px;
        }
      }
      .qty {
        font-size: 24px;
      }
    }
  }
  .title {
    font-weight: bold;
    padding: 0px 0px 20px;
  }
  .pad {
    padding: 30px;
  }
  .address-wrap {
    padding: 30px 30px 40px;
    border-radius: 10px;
    background-color: var(--color-background);
    display: flex;
    align-items: center;
    position: relative;
    &.lin::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      height: 10px;
      width: 100%;
      background: var(--repeating-linear);
    }
    .address-box {
      margin-left: 20px;
      flex-grow: 1;
      .consignee {
        margin-bottom: 10px;
        color: var(--color-default);
        .name {
          font-weight: bold;
          margin-right: 10px;
        }
      }
      .address {
        font-size: 26px;
        line-height: 1.6em;
      }
    }
    .placeholder {
      font-size: 24px;
      color: var(--color-gray);
    }
  }
  .box {
    padding: 10px 30px;
    .row {
      display: flex;
      margin: 40px 0;
      justify-content: space-between;
      align-items: center;
      line-height: 1;
      font-size: 26px;
      &.break {
        flex-wrap: wrap;
        align-items: flex-start;
        .value {
          padding-top: 0px;
          margin-left: -20px;
        }
      }
      .label {
        flex-shrink: 0;
        width: 5em;
        color: var(--color-gray);
        margin-left: 10px;
      }
    }
    .price {
      color: var(--color-danger);
    }
    .remark {
      display: flex;
      color: var(--color-gray);
      align-items: center;
    }
    .marr {
      margin-right: 10px;
    }
  }
}
</style>
